<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of model
 *
 * @author user
 */
class Model {

    protected $db;
    protected $_result;
    protected $_table;

    public function __construct($table = '') {
        $this->db = & Database::handler();

        $this->_table = ($table == '') ?
                strtolower(get_class($this)) :
                $table;
    }

    public function __toString() {
        return get_class($this) . ' model';
    }

    function select_all() {
        $query = 'select * from `' . $this->_table. '`';
        return $this->query($query);
    }

    function select($id) {
        $query = 'select * from `' . $this->_table. '` where `id`=\'' . mysql_real_escape_string($id) . '\'';
        return $this->query($query, TRUE);
    }

    function query($query, $single_result = FALSE) {
        $this->_result = mysql_query($query, $this->db);

        if (preg_match("/select/i", $query)) {
            $result = array();
            $table = array();
            $field = array();
            $temp_results = array();
            $num_of_fields = mysql_num_fields($this->_result);

            for ($i = 0; $i < $num_of_fields; ++$i) {
                array_push($table, mysql_field_table($this->_result, $i));
                array_push($field, mysql_field_name($this->_result, $i));
            }

            while ($row = mysql_fetch_row($this->_result)) {
                for ($i = 0; $i < $num_of_fields; ++$i) {
                    $table[$i] = trim(ucfirst($table[$i]), "s");
                    $temp_results[$table[$i]][$field[$i]] = $row[$i];
                }

                if ($single_result === TRUE) {
                    mysql_free_result($this->_result);
                    return $temp_results;
                }

                array_push($result, $temp_results);
            }

            mysql_free_result($this->_result);
            return ($result);
        }
    }
    
    function get_num_rows() {
        return mysql_num_rows($this->_result);
    }

    function free_result() {
        mysql_free_result($this->_result);
    }

}

?>
